import APIConfig from '../configs/api'
import exceptionMessage from '../configs/exception-message'
import {promisic} from './util'

class Http {
    static async request({url, data, method = 'POST', refetch = true}) {
        let res
        try {
            res = await promisic(wx.request)({
                url: APIConfig.baseUrl + url,
                data,
                method,
                header: {
                    authorization: wx.getStorageSync('authorization') || ''
                }
            })
        } catch (e) {
            Http._showError(-1)
            throw new Error(e.errMsg)
        }
        if (res.data.status < 400) {
            return res.data
        }
        if (res.data.status === 403) {
            const dialogRes = await wx.showModal({
                title: '温馨提示',
                content: '需要您授权头像和昵称才能开放该功能',
                confirmText: '前往'
            })
            if(dialogRes.cancel) return
            wx.reLaunch({
              url: '/pages/login/login'
            })
            return
        }
        if(res.data.status !== 405) {
            Http._showError(res.data.status, res.data.msg)
            const error = Http._generateMessage(res.data.msg)
            throw Error(error)
        }
    }

    static _showError(errorCode, message) {
        let title = ''
        const errorMessage = exceptionMessage[errorCode]
        title = errorMessage || message || '未知异常'

        title = Http._generateMessage(title)
        wx.showToast({
            title,
            icon: 'none',
            duration: 3000
        })
    }

    static _generateMessage(message) {
        return typeof message === 'object' ? Object.values(message).join(';') : message
    }
}

export {Http}
